package com.atguigu.bigdata.gmall.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.bigdata.gmall.realtime.app.BaseAppV1;
import com.atguigu.bigdata.gmall.realtime.bean.questionCountPOJO;
import com.atguigu.bigdata.gmall.realtime.common.Constant;
import com.atguigu.bigdata.gmall.realtime.util.AtguiguUtil;
import com.atguigu.bigdata.gmall.realtime.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

public class Dws_04_questionsAnswerWindow extends BaseAppV1 {
    public static void main(String[] args) {
        new Dws_04_questionsAnswerWindow().init(
                4111,
                2,
                "Dws_04_questionsAnswerWindow",
                Constant.TOPIC_DWD_EXAM_WITH_QUESTIONANDID_DETAIL
        );
    }
    @Override
    protected void handle(StreamExecutionEnvironment env, DataStreamSource<String> stream) {
        //封装到一个pojo中
        SingleOutputStreamOperator<questionCountPOJO> pojoStream = toPOJI(stream);
        //开窗聚合
        SingleOutputStreamOperator<questionCountPOJO> streamOperator = AggWindow(pojoStream);

        //写出到clickhouse
        writeToClickhouse(streamOperator);

    }

    private void writeToClickhouse(SingleOutputStreamOperator<questionCountPOJO> streamOperator) {
        streamOperator
                .addSink(FlinkSinkUtil.getClickHouseSink("dws_question_AnswerAndUserRate_window"
                        , questionCountPOJO.class));
    }

    private SingleOutputStreamOperator<questionCountPOJO> AggWindow(SingleOutputStreamOperator<questionCountPOJO> pojoStream) {
        return pojoStream
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy
                                .<questionCountPOJO>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                                .withTimestampAssigner((bean,ts) -> bean.getTs())
                                .withIdleness(Duration.ofMillis(1))
                ).keyBy(bean -> bean.getQuestionId())
                .window(TumblingEventTimeWindows.of(Time.seconds(5)))
                .reduce(
                        new ReduceFunction<questionCountPOJO>() {
                            @Override
                            public questionCountPOJO reduce(questionCountPOJO value1, questionCountPOJO value2) throws Exception {
                                value1.setCorrectAnswerTimes(value1.getCorrectAnswerTimes()+ value2.getCorrectAnswerTimes());
                                value1.setAnswerTimes(value1.getAnswerTimes()+ value2.getAnswerTimes());
                                value1.setAnswerAloneUser(value1.getAnswerAloneUser()+ value2.getAnswerAloneUser());
                                value1.setCorrectAnswerAloneUser(value1.getCorrectAnswerAloneUser()+ value2.getCorrectAnswerAloneUser());
                                return value1;
                            }
                        },
                        new ProcessWindowFunction<questionCountPOJO, questionCountPOJO, String, TimeWindow>() {
                            @Override
                            public void process(String s,
                                                ProcessWindowFunction<questionCountPOJO, questionCountPOJO, String, TimeWindow>.Context context,
                                                Iterable<questionCountPOJO> iterable,
                                                Collector<questionCountPOJO> collector) throws Exception {
                                questionCountPOJO bean = iterable.iterator().next();
                                bean.setCorrectRate(bean.getCorrectAnswerTimes()/bean.getAnswerTimes().doubleValue());
                                bean.setStt(AtguiguUtil.toDatTime(context.window().getStart()));
                                bean.setEdt(AtguiguUtil.toDatTime(context.window().getEnd()));
                               bean.setTs(System.currentTimeMillis());
                               collector.collect(bean);


                            }
                        }
                );
    }

    private SingleOutputStreamOperator<questionCountPOJO> toPOJI(DataStreamSource<String> stream) {
        return stream
                .map(JSON::parseObject)
                .keyBy(obj -> obj.getString("user_id"))
                .map(new RichMapFunction<JSONObject, questionCountPOJO>() {

                    private ValueState<String> dateState;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        dateState = getRuntimeContext().getState(new ValueStateDescriptor<String>("dateState", String.class));

                    }

                    @Override
                    public questionCountPOJO map(JSONObject value) throws Exception {
                        String questionId = value.getString("question_id");
                        Long ts = value.getLong("ts");

                        //
                        String data = dateState.value();
                        String today = AtguiguUtil.toDate(ts * 1000);

                        Long avAnswer = 0L;
                        if (!today.equals(data)) {
                            avAnswer =1l;
                            dateState.update(today);
                        }
                        Long correct = 0L;
                        Double cc = 0d;
                        if ("1".equals(value.getString("is_correct"))) {
                            cc = 1d;
                            correct=1l;
                        }


                        return new questionCountPOJO("","",questionId,correct,1l,cc,correct,
                                avAnswer,ts*1000);
                    }
                });
        }

    }

